﻿using System;
using System.DirectoryServices.Protocols;
using System.Collections;
using System.Security.Principal;
using System.Collections.Generic;

namespace ActiveDirectoryUtilities.DirectoryServiceAccess
{
	public enum ForestMode
	{
		Windows_2000,
		Windows_2003_Interim,
		Windows_2003,
		Windows_2008,
		Windows_2008_R2,
		Windows_8
	}
	
	public class Forest
    {
        private RootDse _rootDse;
        private string _forestDN, _forestFqdn;

        public string ForestDn { get { return _forestDN; } }
        public string ForestFqdn { get { return _forestFqdn; } }
		public ForestMode ForestFunctionalLevel { get { return _rootDse.ForestFunctionality; } }

        static public Forest GetCurrentForest()
        {
			return new Forest(new RootDse());
        }

        static public Forest GetForest(string connectionPoint)
        {
            return new Forest(new RootDse(connectionPoint));
        }

        private Forest(RootDse root)
        {
			_rootDse = root;
			_forestDN = _rootDse.RootDomainNamingContext.ToLowerInvariant();
            _forestFqdn = _forestDN.Replace("dc=", "").Replace(',', '.');
        }

        public List<Domain> Domains
        {
            get
            {
                WLdapSearchRequest domainSearch =
                    new WLdapSearchRequest(_rootDse.DnsHostName
                    , 389
                    , "CN=Partitions," + _rootDse.ConfigurationNamingContext
                    , Domain.LDAP_SEARCH_FILTER_DOMAIN
                    , SearchScope.Subtree
                    , Domain.domainObjectPropertiesToLoad);

                WLdapSearchResultCollection domainCrossRefs = domainSearch.FindAll();


                List<Domain> domains = new List<Domain>();
                foreach (SearchResultEntry sre in domainCrossRefs)
                {
                    domains.Add(new Domain(sre));
                }
				domains.Sort();
                return domains;
            }
        }
    }
}
